package com.xiegang.serviceMap.remote;

import com.xiegang.internalcommon.constant.AmapConfigConstants;
import com.xiegang.internalcommon.dto.ResponseResult;
import com.xiegang.internalcommon.response.TrackResponse;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author xieGang
 * @description
 * @date 2023/4/5 12:39
 **/
@Service
public class TrackClient {

    @Value("${Amap.key}")
    private String key;

    @Value("${Amap.sid}")
    private String sid;

    @Autowired
    private RestTemplate restTemplate;

    public ResponseResult<TrackResponse> add(String tid){

        StringBuilder url = new StringBuilder();
        url.append(AmapConfigConstants.TRACK_ADD_URL);
        url.append("?");
        url.append("key=");
        url.append(key);
        url.append("&");
        url.append("sid=");
        url.append(sid);
        url.append("&");
        url.append("tid=");
        url.append(tid);

        ResponseEntity<String> forEntity = restTemplate.postForEntity(url.toString(),null, String.class);

        String body = forEntity.getBody();
        JSONObject result = JSONObject.fromObject(body);
        JSONObject data = result.getJSONObject("data");
        String trid = data.getString("trid");
        String trname = "";
        if(data.has("trname")){
            trname = data.getString("trname");
        }

        TrackResponse trackResponse = new TrackResponse();
        trackResponse.setTrid(trid);
        trackResponse.setTrname(trname);
        return ResponseResult.success(trackResponse);
    }
}
